from django.db import models
from shop.models import Product
from decimal import Decimal
from django.core.validators import MinValueValidator, MaxValueValidator
from coupons.models import Coupon


# Create your models here.

class Order(models.Model):
    first_name = models.CharField(max_length=50, verbose_name='姓')
    last_name = models.CharField(max_length=50, verbose_name='名')
    email = models.EmailField(verbose_name='电子邮件')
    address = models.CharField(max_length=250, verbose_name='地址')
    postal_code = models.CharField(max_length=20, verbose_name='邮政编码')
    city = models.CharField(max_length=100, verbose_name='城市')
    created = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    paid = models.BooleanField(default=False, verbose_name='是否付款')
    braintree_id = models.CharField(max_length=50, blank=True)
    coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL,
                               verbose_name='优惠券')
    discount = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100)],
                                   verbose_name='折扣')

    class Meta:
        ordering = ('-created',)
        verbose_name_plural = verbose_name = '订单'

    def __str__(self):
        return f'Order {self.id}'

    # 获得当前订单的总金额
    def get_total_cost(self):
        total_cost = sum(item.get_cost() for item in self.items.all())
        return total_cost - total_cost * (self.discount / Decimal('100'))


class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE, verbose_name='订单')
    product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE, verbose_name='商品')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    quantity = models.PositiveIntegerField(default=1, verbose_name='数量')

    def __str__(self):
        return f'{self.id}'

    # 当前商品的总价
    def get_cost(self):
        return self.price * self.quantity
